package com.heima.app.gateway.filter;

import com.heima.utils.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Slf4j
@Component
public class AuthFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取请求以及响应对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //判断请求是否是登录请求
        boolean login = request.getURI().getPath().contains("login");
        if (login) {
            // 如果是登录请求，放行
            return chain.filter(exchange);
        }
        //获取请求头里面的token字段
        String token = request.getHeaders().getFirst("token");
        //判断token是否为空
        if (StringUtils.isBlank(token)) {
            //设置状态码
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            //返回错误结果
            return response.setComplete();
        }
        try {
            //校验token  通过token获取存储的用户信息
            Claims claimsBody = AppJwtUtil.getClaimsBody(token);
            int i = AppJwtUtil.verifyToken(claimsBody);
            if (i == 1 || i == 2) {
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return response.setComplete();
            }
        }catch (Exception e){
            e.printStackTrace();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        return chain.filter(exchange);
    }

    /*值越小优先级越高*/
    @Override
    public int getOrder() {
        return 0;
    }
}
